package com.sky.common.node.matcher;

import com.sky.business.sys.domain.ContainerConfig;
import com.sky.business.sys.domain.Node;
import com.sky.common.config.CacheConstants;
import lombok.extern.slf4j.Slf4j;

/**
 * 节点资源需求匹配器
 */
@Slf4j
public class ResourceSufficientNodeMathcher implements NodeMathcher {


    @Override
    public boolean match(Node node, ContainerConfig containerConfig) {
        //cpu
        double idleCpuPhysicalCore  = node.getCpuIdlePercent()/100.0*node.getCpuPhysicalCore();
        if(idleCpuPhysicalCore< CacheConstants.IDLE_CPU_PHYSICAL_CORE_MIN){
            log.info("cpu不满足,node:{} , idleCpuPhysicalCore:{}",node.getIpAddr(),idleCpuPhysicalCore);
            return false;
        }
        int maxMemory = Math.max(Math.max(containerConfig.getMemory(),containerConfig.getSharedMemory()),containerConfig.getKernelMemory());
        int requireMemory = maxMemory * 2;
        if(requireMemory< CacheConstants.MIN_REQUIRE_MEMORY_MB){
            requireMemory = CacheConstants.MIN_REQUIRE_MEMORY_MB;
        }
        //内存
        if(node.getFreeMemory()<requireMemory){
            log.info("freeMemory不满足,node:{} , requireMemory:{} , freeMemory:{}",node.getIpAddr(),requireMemory,node.getFreeMemory());
            return false;
        }
        //硬盘
        int requireDiskSpace = CacheConstants.MIN_REQUIRED_DISK_SPACE_MB;
        if(node.getDiskFree()<requireDiskSpace){
            log.info("硬盘不满足,node:{} , requireDiskSpace:{} , diskFree:{}",node.getIpAddr(),requireDiskSpace,node.getDiskFree());
            return false;
        }
        //镜像是否需要支持gpu
        if(containerConfig.getGpuSupport()){
            //节点没有显卡
            if(node.getGpuCount()==0){
                log.info("没有gpu,node:{} ",node.getIpAddr());
                return false;
            }
            //节点显存不足
            if(node.getGpuIdleMemory()<CacheConstants.MIN_REQUIRE_GPU_MEMORY_MB){
                log.info("gpu显存不足,node:{} ",node.getIpAddr());
                return false;
            }
        }
        return true;
    }
}
